import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.FileInputStream;

/**
 * 代码分离器：输出多个指定的文件
 * 输入文件格式：
 * 文件名（单独一行）
 * 文件内容（多行）
 * 其他文件名
 * 其他文件内容（多行）
*/
public class CodeSeparator {
	/** 后缀名识别列表 */
	public static String[] suffix = {".xml", ".java", ".sql", ".jsp", ".html"};
	
	public static void main(String[] args) {
		String filename = "codes.txt";
		String dir = "./src/";
		if (args.length > 0) {
			filename = args[0];
		}
		if (args.length > 1) {
			dir = args[1];
		}
		
		// System.out.println("hello".substring(-1)); 
		// Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
		createDir(dir);
		separatingFile(filename, dir);
	}
	
	public static void createDir(String dir) {
		File file = new File(dir);
		boolean flag = file.mkdir();
		System.out.println("mkdir: " + flag);
	}
	
	public static void separatingFile(String filename, String dir) {
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			//br = new BufferedReader(new FileReader(filename));
			br = new BufferedReader(new InputStreamReader(new FileInputStream(filename),"UTF-8"));
			String line = null;
			while ((line = br.readLine()) != null) {
				line = line.trim();		// 去掉开头和结尾的空格,否则识别文件名和提取文件名会出现遗漏情况
				if (isFileName(line)) {
					String newFileName = parseFileName(line);
					System.out.println(newFileName);
					if (bw != null) {
						bw.close();
						bw = null;
					}
					bw = new BufferedWriter(new FileWriter(dir + "/" + newFileName));
				} else {
					if (bw != null) {
						bw.write(line);
		                bw.newLine(); //换行
					}
				}
			}
			if (bw != null) {
				bw.close();
			}
			if (br != null) {
				br.close();
			}			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static boolean isFileName(String line) {
		for (String i : suffix) {
			if (line.endsWith(i)) {
				return true;
			}
		}
		return false;
	}
	
	public static String parseFileName(String line) {
		int i = line.lastIndexOf(' ');
		if (i == -1) {
			return line.trim();
		}
		return line.substring(i).trim();
	}
}